import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../lib_basemodel/user/user.dart';
import '../../lib_baseview/provider.dart';
import '../../lib_baseview/utils/cache_util.dart';
import '../../lib_network/http_api.dart';
import '../../lib_network/http_helper.dart';
import '../../lib_user/user_manager.dart';
import '../../m_main/main/main_page.dart';

class VeriCodeModel extends JRChangeNotifier {
  /// 手机号和验证码
  late String phoneNumStr;
  late String veriCodeStr;

  VeriCodeModel(this.phoneNumStr, this.veriCodeStr) {
    /// 初始化方法
  }

  String _inputCodeStr = '';

  String get inputCodeStr => _inputCodeStr;

// 修改设置方法
  void setInputCodeStr(String codeStr) {
    _inputCodeStr = codeStr;
    // validateInput(); // 添加验证
    notifyListeners();
  }

  /// 调用获取验证码接口
  reloadVeriCode() async {
    var response = await HttpHelper.instance().post(
      HttpApi.smsVerify,
      body: {"mobile": phoneNumStr, "areaCode": veriCodeStr},
      showLoading: false,
      showToast: true,
    );
    if (response.isSuccess) {
      // Get.to(() => VeriCodePage(
      //     phoneNum: textController.text.trim(), areaCode: areaCode!));
    }
  }

  /// 登录请求
  loginAction(BuildContext context, String codeStr) async {
    var response = await HttpHelper.instance().post(
      HttpApi.login,
      body: {"areaCode": veriCodeStr, "mobile": phoneNumStr, "code": codeStr},
      showLoading: true,
      showToast: true,
    );
    if (response.isSuccess) {
      // print("")
      if (response.result == null) {
        print("登录报错");
        // Get.to(() => MainPage());
      } else {
        // 这里应该有个登录管理者，在登录管理者

        User user = User.fromJson(response.result);
        UserManager.instance.updateUserInfo(user);
        CacheUtil.set(CacheKeys.userCacheKey, json.encode(user.toJson()));

        if (user.id != null) {
          String cacheKey =
              CacheKeys.userLoginCountCacheKey((user.id).toString());
          UserManager.instance.incrementLoginCount(cacheKey);
        }

        // if (user.country == null) {
        //   Navigator.of(context).push(CupertinoPageRoute(builder: (context) {
        //     return const InformationPage();
        //   }));
        // } else {
        // Navigator.of(context).pushAndRemoveUntil(
        //   CupertinoPageRoute(builder: (context) => MainPage()),
        //   (route) => false, // 这个条件会移除所有历史路由
        // );
        // Get.offAll(() => MainPage());
        Get.until((route) => route.isFirst);

        // }
      }
    } else {
      print("登录失败");
      // inputCodeStr = '';
      setInputCodeStr('');
      notifyListeners();
    }
  }
}
